import logging
from blog.settings import dev
from blog_project.models import *
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from django.db.models import Count

# Create your views here.


def global_setting(request):
    # 站点基本信息
    SITE_NAME = dev.SITE_NAME
    SITE_DESC = dev.SITE_DESC
    # 文章归档数据
    archive_list = Article.objects.distinct_date()
    # 分类信息获取（导航数据）
    category_list = Category.objects.all()[:1]
    # 广告数据(for 标签显示在模版上)
    # 标签云数据
    # 友情链接
    # 文章排行榜
    # 评论排行
    comment_count_list = Comment.objects.values('article').annotate(comment_count=Count('article')).order_by('-comment_count')
    article_comment_list = [Article.objects.get(pk=comment['article']) for comment in comment_count_list]
    return locals()


logger = logging.getLogger('blog.apps.blog_project.views')


def index(request):
    try:
    # 广告数据(for 标签显示在模版上)
    # 最新文章数据
        article_list = Article.objects.all()
        article_list = getPage(request, article_list)

    except Exception as e:
        print(e)
        logger.error(e)
    return render(request, 'index.html', locals())


def archive(request):
    try:
        # 先获取客户端提交的信息
        year = request.Get.get('year', None)
        month = request.Get.get('month', None)
        article_list = Article.objects.filter(date_publish_icontains=year + '-' + month)  # 模糊查询
        article_list = getPage(request, article_list)
    except Exception as e:
        logger.error(e)

    return render(request, 'archive.html', locals())


# 分页代码
def getPage(request, article_list):
    # article_list = Article.objects.all()  # 在models中默认文章按日期倒序排列
    paginator = Paginator(article_list, 2)
    try:
        page = int(request.Get.get('page', 1))
        article_list = paginator.page(page)
    except(EmptyPage, InvalidPage, PageNotAnInteger):
        article_list = paginator.page(1)
    return article_list


def hello_world(request):
    a = 'hello world'
    return HttpResponse(a)
